package Z.dailyExercise._1221;

public class _14_最长公共前缀 {
    /**
     * 自解：先对比前两个获得最大公共 再用结果往后比对
     * --思路可以 代码不合适
     * 可以分函数写法
     * @param strs
     * @return
     */
    public String longestCommonPrefix(String[] strs) {


        if (strs.length<1){
            return "";
        }
        if (strs.length == 1){
            return strs[0];
        }
        int len1 = strs[0].length();
        int len2 = strs[1].length();

        StringBuffer sb = new StringBuffer();
        for (int i=0;i< len1 && i<len2;i++){
           if (strs[0].charAt(i)==strs[1].charAt(i)){
               sb.append(strs[1].charAt(i));
           }else {
               break;
           }
        }

        if (sb.length()<=0){
            return "";
        }
        //遍历其后的strs
        for (int i=2;i<strs.length;i++){
            for (int j=0;j<strs[i].length() && j<sb.length();j++){
                if (strs[i].charAt(j) == sb.charAt(j)){
                    continue;
                }else {
                    sb.delete(j,sb.length());
                    break;
                }
            }

            if (sb.length()<=0){
                return "";
            }

        }

        return sb.toString();


    }

    public String longestCommonPrefix1(String[] strs){

        if (strs == null || strs.length == 0){
            return "";
        }
        String compare = strs[0];

        for (int i=1;i<strs.length;i++){

            compare = compare(compare,strs[i]);
            if (compare.length() == 0){
                break;
            }

        }

        return compare;
    }

    public String compare(String str1,String str2){

        int len = Math.min(str1.length(),str2.length());
        int index = 0;
        //直接截index即可
        while (index < len && str1.charAt(index) == str2.charAt(index)){
                index++;

        }

        return str1.substring(0,index);

    }

}
